Writing Health Quantity Samples PRO
The Scripting app allows you to write quantity-based health data (such as step count, heart rate, calories, and more) to Apple HealthKit using the HealthQuantitySample class and the Health.saveQuantitySample method.
This guide explains how to create and save a new quantity sample.
Prerequisites
-
Ensure HealthKit is available on the device:
-
Make sure your script has the appropriate write permission for the quantity type you want to save. Permissions are requested automatically when you call save APIs.
1. Create a HealthQuantitySample
Use HealthQuantitySample.create() to instantiate a new sample.
Parameters
type: AHealthQuantityTypestring, such as"stepCount","heartRate","bodyMass", etc.startDate: The start of the measurement period (a JavaScriptDateobject).endDate: The end of the measurement period (a JavaScriptDateobject).value: The numeric value of the sample.unit: AHealthUnitrepresenting the measurement unit (e.g.,HealthUnit.count(),HealthUnit.gram(),HealthUnit.meter()).metadata(optional): An object containing additional metadata.
Example
2. Save the Quantity Sample
After creating the sample, use Health.saveQuantitySample() to store it in the HealthKit database.
If saving fails (e.g., due to missing permissions), the promise will reject with an error.
Full Example
Notes
-
The unit must match the type. For example:
"stepCount"→HealthUnit.count()"bodyMass"→HealthUnit.gram(HealthMetrixPrefix.kilo)"heartRate"→HealthUnit.count().divided(HealthUnit.minute())
-
If the sample’s type is cumulative (e.g., steps, distance), the
startDateandendDateshould cover the time window over which the value was measured.
